﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;

namespace WindowsApplication1
{
    public partial class ResWindow : Form
    {
        public ResWindow(int eventID, int RaceId)
        {
            this.EventID = eventID;
            this.RaceID = RaceId;
            InitializeComponent();
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            LoadClasses();
            if (currentClasses.Count > 0)
            {
                currentFirstDisplayClass = currentClasses[0];
            }
            timer2_Tick(null, new EventArgs());
        }

        public int EventID { get; set; }
        public int RaceID { get; set; }

        bool m_HighContrast = false;
        public bool HighContrast
        {
            get
            {
                return m_HighContrast;
            }
            set
            {
                m_HighContrast = value;
                if (m_HighContrast)
                {
                    BackColor = Color.Black;
                    ForeColor = Color.White;
                }
                else
                {
                    BackColor = Color.WhiteSmoke;
                    ForeColor = Color.Black;

                }

                this.Invalidate();
            }
        }

        int eventId = 14;
        int raceId =14;
        class Class : IComparable, IComparable<Class>
        {
            public int classID;
            public string Name;

            #region IComparable Members

            public int CompareTo(object obj)
            {
                if (obj is Class)
                {
                    Class c = obj as Class;
                    return classID.CompareTo(c.classID);
                }
                else
                    throw new ApplicationException("Error");
            }

            #endregion

            #region IComparable<Class> Members

            public int CompareTo(Class other)
            {
                return classID.CompareTo(other.classID);
            }

            #endregion
        }

        List<Class> currentClasses = new List<Class>();
        Class currentFirstDisplayClass = null;
        private void LoadClasses()
        {
            MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(ConfigurationManager.AppSettings["OLACONN"]);
            try
            {
                conn.Open();
                MySql.Data.MySqlClient.MySqlCommand cmd = conn.CreateCommand();

                cmd.CommandText = "select raceClassId, name from raceclasses, eventclasses where eventclasses.eventid = " + EventID + " and raceclasses.eventclassid = eventclasses.eventclassid and eventRaceId = " + RaceID;
                IDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Class c = new Class();
                    c.classID = Convert.ToInt32(reader["raceClassId"]);
                    if (currentClasses.Contains(c))
                    {
                        int idx = currentClasses.IndexOf(c);
                        currentClasses[idx].Name=reader["name"] as string;
                    }
                    else
                    {
                        c.Name = reader["name"] as string;
                        currentClasses.Add(c);
                    }
                }
                reader.Close();

            }
            catch (Exception ee)
            {
                lastErr = ee.Message;
            }
            finally
            {
                conn.Close();
            }
        }
        string lastErr = "";
        private void ResWindow_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.Close();
            }
        }

        string currentDisplayClass = "H21";
        List<Result> currentDisplayResults = new List<Result>();
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (!string.IsNullOrEmpty(lastErr))
            {
                e.Graphics.DrawString(lastErr, new Font("Arial", 10f), Brushes.Red, 0, 0);
            }
            float sx = 5;
            float sy = 5;

            StringFormat sf = new StringFormat();
            float[] ts = { 20.0f, 25.0f, 280.0f, 280.0f, 50.0f };
            sf.SetTabStops(0.0f, ts);


            Font f = new Font("Arial Black", 24f);
            if (currentFirstDisplayClass != null)
            {
                string header = "Resultat " + currentFirstDisplayClass.Name + " - " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                sy = DrawString(e, sx, sy, f, header, sf);
            }
            else
            {
                string header = "Hittar inga klasser ännu - " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                sy = DrawString(e, sx, sy, f, header, sf);
            }
            f = new Font("Arial",22f);
            /* draw results*/

            List<Result> results = currentDisplayResults;
            if (results == null || results.Count == 0)
            {
                sy = DrawString(e, sx, sy, f, "Inga resultat i denna klass ännu..",sf);
            }
            else
            {
                int place = 1;
                int firstTime = 0;
                foreach (Result r in results)
                {
                    if (place == 1)
                        firstTime = r.TotalTime;
                    string placeStr = place.ToString() + ".";
                    string timeStr = formatTime(r.TotalTime);
                    string timePlusStr = "+" + formatTime(r.TotalTime - firstTime);
                    if (r.status != 0)
                    {
                        placeStr = "   ";
                        timePlusStr = "   ";
                        switch (r.status)
                        {case 1:
                            timeStr = "Ej Start";
                            break;
                            case 4:
                                timeStr = "Disq.";
                                break;
                            case 3:
                                timeStr = "Felst.";
                                break;
                            case 11:
                                timeStr = "Utgått";
                                break;
                            case 12:
                                timeStr = "Uppfl.";
                                break;
                        }
                    }
                    sy = DrawString(e, sx, sy, f, placeStr + "\t" + r.RunnerName + "\t" + r.RunnerClub + "\t" + timeStr + "\t" + timePlusStr + "", sf);
                    place++;
                }
            }
        }

        string formatTime(int time)
        {
            //int hours = time / 360000;
            //time -= hours * 360000;
            int minutes = time / 6000;
            time -= minutes * 6000;
            int seconds = time / 100;

            return minutes.ToString().PadLeft(2, '0') + ":" + seconds.ToString().PadLeft(2, '0');
        }

        private float DrawString(PaintEventArgs e, float sx, float sy, Font f, string header,StringFormat sf)
        {
            RectangleF    enclosingRectangle = new RectangleF(sx, sy, this.Width, e.Graphics.MeasureString(header,f).Height);
            e.Graphics.DrawString(header, f, new SolidBrush(ForeColor), sx, sy, sf);
            sy += e.Graphics.MeasureString(header, f, 2000, sf).Height;
            return sy;
        }

        class Result
        {
            public int place;
            public string RunnerName;
            public string RunnerClub;
            public int TotalTime;
            public int status;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Invalidate();
        }

        string lastmodDate = "2000-01-01 00:00:00";
        private void timer2_Tick(object sender, EventArgs e)
        {
            if (currentClasses.Count < 1)
                return;

            timer2.Enabled = false;
            int idx = currentClasses.IndexOf(currentFirstDisplayClass);
            if (idx >= currentClasses.Count - 1)
            {
                idx = 0;
            }
            else
            {
                idx++;
            }
            currentFirstDisplayClass = currentClasses[idx];

            /* Load Next results*/
             MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(ConfigurationManager.AppSettings["OLACONN"]);
            try
            {
                string className = currentFirstDisplayClass.Name;
                conn.Open();
                MySql.Data.MySqlClient.MySqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "select results.modifyDate, results.totalTime, results.position, persons.familyname as lastname, persons.firstname as firstname, clubs.shortname as clubname, eventclasses.shortName, results.runnerStatus, results.entryid from results, entries, Persons, Clubs, raceclasses,eventclasses where raceclasses.eventClassID = eventClasses.eventClassID and results.raceClassID = raceclasses.raceclassid and raceClasses.eventRaceId = " + RaceID + " and eventclasses.eventid = " + EventID + " and results.entryid = entries.entryid and entries.competitorid = persons.personid and persons.clubid = clubs.clubid and results.runnerStatus != 'notActivated' and eventclasses.name = '" + className + "' order by runnerStatus, totalTime";// and results.modifyDate > '" + lastmodDate + "'";
                IDataReader reader = cmd.ExecuteReader();
                List<Result> res = new List<Result>();
                while (reader.Read())
                {
                    //string modDate = reader["modifydate"] as string;
                    Result r = new Result();
                    if (reader["position"] != DBNull.Value)
                    {
                        r.place = Convert.ToInt32(reader["position"]);
                    }
                    else
                    {
                        r.place = -1;
                    }
                    r.RunnerClub = reader["clubname"] as string;
                    r.RunnerName = reader["firstname"] as string + " " + reader["lastname"] as string;
                    r.TotalTime = -1;
                    if (reader["totaltime"] != DBNull.Value)
                    {
                        r.TotalTime = Convert.ToInt32(reader["totaltime"]);
                    }

                    int rstatus = 0;
                    string status = reader["runnerStatus"] as string;
                    switch (status)
                    {
                        case "started":
                            rstatus = 9;
                            break;
                        case "notActivated":
                            rstatus = 10;
                            //rstatus = EMMAClient.RunnerStatus.NotStartedYet;
                            break;
                        case "notStarted":
                            rstatus = 1;
                            //rstatus = EMMAClient.RunnerStatus.NotStarted;
                            break;
                        case "disqualified":
                            rstatus = 4;
                            break;
                        case "notValid":
                            rstatus = 3;
                            //rstatus = EMMAClient.RunnerStatus.MissingPunch;
                            break;
                        case "walkOver":
                            rstatus = 11;
                            //rstatus = EMMAClient.RunnerStatus.WalkOver;
                            break;
                        case "movedUp":
                            rstatus = 12;
                            //rstatus = EMMAClient.RunnerStatus.MovedUp;
                            break;
                    }
                    r.status = rstatus;
                    res.Add(r);
                    
                }
                reader.Close();

                res.Sort(new Comparison<Result>(delegate(Result r1, Result r2)
                {
                    if (r1.status != r2.status)
                        return r1.status.CompareTo(r2.status);
                    else
                        return r1.TotalTime.CompareTo(r2.TotalTime);
                }
                ));

                lock (currentDisplayResults)
                {
                    currentDisplayResults = res;
                }

                timer2.Interval = 7000 + Math.Max(0, res.Count - 5) * 1000;

            }
            catch (Exception ee)
            {
                lastErr = ee.Message;
            }
            finally
            {
                conn.Close();
            }
            timer2.Enabled = true;
        }
    }
}